package com.xxwy.dependency.scope;

import com.xxwy.dependency.User;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * 原型作用域.
 *
 * @author xxwy
 * @date 2021/7/14 0014
 */
@Configuration
public class PrototypeDemo implements DisposableBean {

    @Autowired
    private User prototype;

    @Autowired
    private User singleton;

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public User prototype() {
        return new User();
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public User singleton() {
        return new User();
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(PrototypeDemo.class);
        applicationContext.refresh();
        PrototypeDemo bean = applicationContext.getBean(PrototypeDemo.class);

        System.out.println("singleton " + bean.singleton);
        System.out.println("prototype " + bean.prototype);

        // 原型Bean 每次依赖查找或者，依赖注入都会创建新的对象
        User prototype = applicationContext.getBean("prototype", User.class);
        System.out.println("prototype " + prototype);

        // 原型Bean,销毁不在spring ioc声明周期内
        // only console : singleton -User PreDestroy
        applicationContext.close();
    }


    @Override
    public void destroy() throws Exception {
        prototype.destroy();
    }
}
